<template>
  <div class="avatar">
    <img :src="avatar" />
    <div v-if="change" class="mask" @click="fileRef.click">更换头像</div>
    <input
      ref="fileRef"
      accept="image/jpg,image/jpeg,image/png,image/gif"
      type="file"
      style="display: none"
      @change="fileChange"
    />
  </div>
</template>

<script lang="ts" setup>
import { computed, onBeforeMount, ref } from 'vue';
import { useApi } from '@core/http/api-instance';
import { useOathStore } from '@core/pinia/stores/oath';
import defaultUser from '@assets/img/user/default-user.svg';
import { ElMessage } from 'element-plus';
const props = defineProps({
  avatar: {
    type: String,
  },
  userId: {
    type: String,
  },
  change: {
    type: Boolean,
    default: false,
  },
});
const api = useApi();
const oathStore = useOathStore();
const fileRef = ref<HTMLInputElement>();

onBeforeMount(() => {
  if (!document.cookie) {
    oathStore.clear();
  }
});

const avatar = computed(() => {
  return props.avatar || oathStore.userInfo.avatar || defaultUser;
});

const emit = defineEmits(['afterChange']);
//更换头像
const fileChange = async () => {
  try {
    const file = Array.from(fileRef.value.files)[0];
    const formData = new FormData();
    formData.append('file', file);
    var avatarUrl = await api.image.uploadImage(formData);
    await api.user.changeAvatar(props.userId, avatarUrl);
    fileRef.value.value = '';
    oathStore.setUserInfo();
    emit('afterChange');
  } catch (e) {
    ElMessage.warning(e instanceof Error && e.message);
  }
};
</script>

<style lang="scss" scoped>
.avatar {
  width: 60px;
  height: 60px;
  overflow: hidden;
  position: relative;
  border-radius: 50%;

  .mask {
    top: 0;
    left: 0;
    opacity: 0;
    width: 100%;
    height: 100%;
    display: flex;
    font-size: 10px;
    position: absolute;
    align-items: center;
    justify-content: center;
    color: var(--white-color);
    transition: opacity 0.4s;
    background-color: rgba(0, 0, 0, 0.3);

    &:hover {
      opacity: 1;
    }
  }

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}
</style>
